<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Example: Attribute Change Events</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.4.0pr3/build/cssgrids/grids-min.css">
    <link rel="stylesheet" href="../assets/css/main.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <script src="../../build/yui/yui-min.js"></script>
</head>
<body>

<div id="doc">
    <h1>Example: Attribute Change Events</h1>

    

    <div class="yui3-g">
        <div id="main" class="yui3-u">
            <div class="content"><style type="text/css" scoped>
    #example-out .event {
        padding:2px 2px 2px 5px;
    }
    
    #example-out .event-props {
        font-family:courier;
        margin-top:2px;
    }

    #example-out .event-title {
        font-weight:bold;
        font-family:arial;
        color:#8dd5e7;
        margin-top:5px;
        margin-bottom:3px;
    }

    #example-out {
        margin:5px;
        border:1px solid #000;
        color:#ffffff;
        background-color:#004c6d;
        overflow:auto;
        height:20em;
    }

    .attrs {
        border:1px solid #000;
        background-color:#cdcdcd;
        margin:5px;
    }

    .attrs .header {
        font-weight:bold;
        background-color:#aaa;
        padding:5px;
    }

    .attrs .body {
        padding:10px;
    }

    .attrs .footer {
        padding:5px;
    }

    .attrs label {
        display:block;
        float:left;
        clear:left;
        font-weight:bold;
        width:8em;
    }

    .attrs #preventFoobar.hidden {
        display:none;
    }

    .attrs #preventFoobar {
        margin-left:5px;
        display:inline;
        float:none;
        clear:none;
    }
</style>

<div class="intro">
    <p>Attribute change events are one of the key benefits of using attributes to maintain state for your objects, instead of regular object properties. This example shows how you can listen for attribute change events and work with the event payload they receive.</p> 
</div>

<div class="example">
    <div class="attrs">
    <div class="header">Enter a new value and click the "Change Value" button:</div>
    <div class="body">
        <p>
            <label for="attrSel">Attribute</label>: 
            <select id="attrSel">
                <option value="foo">foo</option>
                <option value="bar">bar</option>
                <option value="foobar">foobar</option>
            </select>
            <label id="preventFoobar" class="hidden"><input type="checkbox" checked="true"> Prevent change</label>
        </p>
        <p><label for="currentVal">Current Value</label>: <span id="currentVal"></span></p>
        <p><label for="newVal">New Value</label>: <input type="text" id="newVal" /></p>
    </div>
    <div class="footer">
        <button type="button" id="changeValue">Change Value</button>
    </div>
</div>

<div id="example-out"></div>

<script type="text/javascript">
// Get a new YUI instance 
YUI().use("node", "attribute", "escape", function(Y) {

    // Setup a custom class with attribute support
    function MyClass(cfg) {

        // Setup attribute configuration
        var attrs = {
            "foo" : {
                value:5
            },
     
            "bar" : {
                value:"Hello World!"
            },
    
            "foobar" : {
                value:true
            }
        };

        this.addAttrs(attrs, cfg);
    }

    Y.augment(MyClass, Y.Attribute);

    var o1 = new MyClass();

    function displayEvent(e, title) {
        var str = '<div class="event"><div class="event-title">' + title + '</div>';

        if (e) {
            str += 
            '<ul class="event-props"><li>e.attrName: ' 
            + e.attrName 
            + '</li><li>e.prevVal: '
            + Y.Escape.html(e.prevVal + "")
            + '</li><li>e.newVal: '
            + Y.Escape.html(e.newVal + "")
            + '</li></ul></div>';
        }

        str += '</div>';
 
        Y.one("#example-out").prepend(str);
    }

    // Start Example Form Handling
    var attrSel = Y.one("#attrSel");
    var newValTxt = Y.one("#newVal");
    var currentValSpan = Y.one("#currentVal");
    var preventFoobarChk = Y.one("#preventFoobar input[type=checkbox]");
    var preventFoobarLbl = Y.one("#preventFoobar");

    var attrOpts = attrSel.get("options");

    function updateVal() {
        var selIndex = attrSel.get("selectedIndex");
        var attr = attrOpts.item(selIndex).get("value");
        o1.set(attr, newValTxt.get("value"));
    }

    Y.on("click", updateVal, "#changeValue");

    function populateCurrentValue() {
        var selIndex = attrSel.get("selectedIndex");
        var attr = attrOpts.item(selIndex).get("value");

        currentValSpan.set("innerHTML", Y.Escape.html(o1.get(attr) + ""));
        newValTxt.set("value", "");

        if (attr === "foobar") {
            preventFoobarLbl.removeClass("hidden");
        } else {
            preventFoobarLbl.addClass("hidden");
        }
    }

    populateCurrentValue();

    Y.on("change", populateCurrentValue, attrSel);
    // End Example Form Handling

    // Attribute Change Event Listners

    o1.after("fooChange", function(e) {
        displayEvent(e, "After fooChange");
        currentValSpan.set("innerHTML", Y.Escape.html(e.newVal+""));
    });

    o1.after("barChange", function(e) {
        displayEvent(e, "After barChange");
        currentValSpan.set("innerHTML", Y.Escape.html(e.newVal+""));
    });

    o1.on("foobarChange", function(e) {

        if (preventFoobarChk.get("checked")) {

            // Calling preventDefault, in an "on" listener
            // will prevent the attribute change from occuring
            // and the after listener being called.

            e.preventDefault();
            displayEvent(null, "On foobarChange (prevented)");
        }

    });

    o1.after("foobarChange", function(e) {

        // This foobar after listener will not get called, 
        // if we end up preventing default in the "on" 
        // listener above.

        displayEvent(e, "After foobarChange");
        currentValSpan.set("innerHTML", Y.Escape.html(e.newVal+""));
    });

});
</script>

</div>

<h2>Listening For Attribute Change Events</h2>

<p>In this example, we'll look at how you can setup listeners for attribute change events, and work with the event payload which the listeners receive.</p>

<h3>Setting Up A Custom Class With Attribute</h3>

<p>We start by setting up the same custom class we created for the <a href="attribute-basic.html">basic example</a> with 3 attributes <code>foo</code>, <code>bar</code> and <code>foobar</code>, using the code below:</p>

<pre class="code prettyprint">YUI().use(&quot;attribute&quot;, &quot;node&quot;, function(Y) {

    &#x2F;&#x2F; Setup a custom class with attribute support
    function MyClass(cfg) {

        &#x2F;&#x2F; Setup attribute configuration
        var attrs = {
            &quot;foo&quot; : {
                value:5
            },
     
            &quot;bar&quot; : {
                value:&quot;Hello World!&quot;
            },
    
            &quot;foobar&quot; : {
                value:true
            }
        };

        this.addAttrs(attrs, cfg);
    }

    Y.augment(MyClass, Y.Attribute);

});</pre>


<h3>Registering Event Listeners</h3>

<p>Once we have an instance of the custom class, we can use the <code>on</code> and <code>after</code> methods provided by Attribute, to listen for changes in the value of each of the attributes:</p>

<pre class="code prettyprint">var o1 = new MyClass();

...

&#x2F;&#x2F; Event Listners
o1.after(&quot;fooChange&quot;, function(e) {
    displayEvent(e, &quot;After fooChange&quot;);
    currentValSpan.set(&quot;innerHTML&quot;, Y.Escape.html(e.newVal+&quot;&quot;));
});

o1.after(&quot;barChange&quot;, function(e) {
    displayEvent(e, &quot;After barChange&quot;);
    currentValSpan.set(&quot;innerHTML&quot;, Y.Escape.html(e.newVal+&quot;&quot;));
});

o1.on(&quot;foobarChange&quot;, function(e) {

    if (preventFoobarChk.get(&quot;checked&quot;)) {

        &#x2F;&#x2F; Calling preventDefault, in an &quot;on&quot; listener
        &#x2F;&#x2F; will prevent the attribute change from occuring
        &#x2F;&#x2F; and the after listener being called.

        e.preventDefault();
        displayEvent(null, &quot;On foobarChange (prevented)&quot;);
    }

});

o1.after(&quot;foobarChange&quot;, function(e) {

    &#x2F;&#x2F; This foobar after listener will not get called, 
    &#x2F;&#x2F; if we end up preventing default in the &quot;on&quot; 
    &#x2F;&#x2F; listener above.

    displayEvent(e, &quot;After foobarChange&quot;);
    currentValSpan.set(&quot;innerHTML&quot;, Y.Escape.html(e.newVal+&quot;&quot;));
});</pre>


<p>As seen in the above code, the event type for attribute change events is created by concatenating the attribute name with <code>&quot;Change&quot;</code> (e.g. <code>&quot;fooChange&quot;</code>), and this event type is used for both the <code>on</code> and <code>after</code> subscription methods. Whenever an attribute value is changed through Attribute's <code>set</code> method, both "on" and "after" subscribers are notified.</p>

<h3>On vs. After</h3>

<p><strong>on :</strong> Subscribers to the "on" moment, will be notified <em>before</em> any actual state change has occurred. This provides the opportunity to prevent the state change from occurring, using the <code>preventDefault</code> method of the event facade object passed to the subscriber. If you use <code>get</code> to retrieve the value of the attribute in an "on" subscriber, you will receive the current, unchanged value. However the event facade provides access to the value which the attribute is being set to, through it's <code>newVal</code> property.</p>

<p><strong>after :</strong> Subscribers to the "after" moment, will be notified <em>after</em> the attribute's state has been updated. This provides the opportunity to update state in other parts of your application, in response to a change in the attribute's state.</p>

<p>Based on the definition above, <code>after</code> listeners are not invoked if state change is prevented, for example, due to one of the <code>on</code> listeners calling <code>preventDefault</code> on the event object, as is done in the <code>on</code> listener for the <code>foobar</code> attribute:</p>

<pre class="code prettyprint">o1.on(&quot;foobarChange&quot;, function(event) {

    &#x2F;&#x2F; Calling preventDefault, in an &quot;on&quot; listener
    &#x2F;&#x2F; will prevent the attribute change from occurring
    &#x2F;&#x2F; and prevent the after listeners from being called
    displayEvent(event, &quot;on foobarChange (change prevented)&quot;);

    event.preventDefault();
});</pre>


<p>For primitive values (non-Object values), the <code>after</code> listeners will also not be invoked if there is no change in the actual value of the attribute. That is, if the new value of the attribute is the same as the current value (based on the identity operator, <code>===</code>), the <code>after</code> listeners will not be notified because there is no change in state. You can see this, by setting an attribute to the same value twice in a row.</p>

<h3>Event Facade</h3>

<p>The event object (an instance of <a href="http://yuilibrary.com/yui/docs/api/EventFacade.html">EventFacade</a>) passed to attribute change event subscribers, has the following interesting properties and methods related to attribute management:</p>

<dl>
    <dt>newVal</dt>
    <dd>The value which the attribute will be set to (in the case of "on" subscribers), or has been set to (in the case of "after" subscribers</dd>
    <dt>prevVal</dt>
    <dd>The value which the attribute is currently set to (in the case of "on" subscribers), or was previously set to (in the case of "after" subscribers</dd>
    <dt>attrName</dt>
    <dd>The name of the attribute which is being set</dd>
    <dt>subAttrName</dt>
    <dd>Attribute also allows you to set nested properties of attributes which have values which are objects through the 
    <code>set</code> method (e.g. <code>o1.set(&quot;x.y.z&quot;)</code>). This property will contain the path to the property which was changed.</dd>
    <dt>preventDefault()<dt>
    <dd>This method can be called in an "on" subscriber to prevent the attribute's value from being updated (the default behavior). Calling this method in an "after" listener has no impact, since the default behavior has already been invoked.</dd>
    <dt>stopImmediatePropagation()</dt>
    <dd>This method can be called in "on" or "after" subscribers, and will prevent the rest of the subscriber stack from
    being invoked, but will not prevent the attribute's value from being updated.</dd>
</dl>

<p>The <a href="attribute-event-speeddate.html">"Attribute Event Based Speed Dating" example</a> provides a look at how you can leverage attribute change events in your applications, to decouple logic both within your class, and when interacting with other objects.</p>

<h2>Complete Example Source</h2>

<pre class="code prettyprint">&lt;div class=&quot;attrs&quot;&gt;
    &lt;div class=&quot;header&quot;&gt;Enter a new value and click the &quot;Change Value&quot; button:&lt;&#x2F;div&gt;
    &lt;div class=&quot;body&quot;&gt;
        &lt;p&gt;
            &lt;label for=&quot;attrSel&quot;&gt;Attribute&lt;&#x2F;label&gt;: 
            &lt;select id=&quot;attrSel&quot;&gt;
                &lt;option value=&quot;foo&quot;&gt;foo&lt;&#x2F;option&gt;
                &lt;option value=&quot;bar&quot;&gt;bar&lt;&#x2F;option&gt;
                &lt;option value=&quot;foobar&quot;&gt;foobar&lt;&#x2F;option&gt;
            &lt;&#x2F;select&gt;
            &lt;label id=&quot;preventFoobar&quot; class=&quot;hidden&quot;&gt;&lt;input type=&quot;checkbox&quot; checked=&quot;true&quot;&gt; Prevent change&lt;&#x2F;label&gt;
        &lt;&#x2F;p&gt;
        &lt;p&gt;&lt;label for=&quot;currentVal&quot;&gt;Current Value&lt;&#x2F;label&gt;: &lt;span id=&quot;currentVal&quot;&gt;&lt;&#x2F;span&gt;&lt;&#x2F;p&gt;
        &lt;p&gt;&lt;label for=&quot;newVal&quot;&gt;New Value&lt;&#x2F;label&gt;: &lt;input type=&quot;text&quot; id=&quot;newVal&quot; &#x2F;&gt;&lt;&#x2F;p&gt;
    &lt;&#x2F;div&gt;
    &lt;div class=&quot;footer&quot;&gt;
        &lt;button type=&quot;button&quot; id=&quot;changeValue&quot;&gt;Change Value&lt;&#x2F;button&gt;
    &lt;&#x2F;div&gt;
&lt;&#x2F;div&gt;

&lt;div id=&quot;example-out&quot;&gt;&lt;&#x2F;div&gt;

&lt;script type=&quot;text&#x2F;javascript&quot;&gt;
&#x2F;&#x2F; Get a new YUI instance 
YUI().use(&quot;node&quot;, &quot;attribute&quot;, &quot;escape&quot;, function(Y) {

    &#x2F;&#x2F; Setup a custom class with attribute support
    function MyClass(cfg) {

        &#x2F;&#x2F; Setup attribute configuration
        var attrs = {
            &quot;foo&quot; : {
                value:5
            },
     
            &quot;bar&quot; : {
                value:&quot;Hello World!&quot;
            },
    
            &quot;foobar&quot; : {
                value:true
            }
        };

        this.addAttrs(attrs, cfg);
    }

    Y.augment(MyClass, Y.Attribute);

    var o1 = new MyClass();

    function displayEvent(e, title) {
        var str = &#x27;&lt;div class=&quot;event&quot;&gt;&lt;div class=&quot;event-title&quot;&gt;&#x27; + title + &#x27;&lt;&#x2F;div&gt;&#x27;;

        if (e) {
            str += 
            &#x27;&lt;ul class=&quot;event-props&quot;&gt;&lt;li&gt;e.attrName: &#x27; 
            + e.attrName 
            + &#x27;&lt;&#x2F;li&gt;&lt;li&gt;e.prevVal: &#x27;
            + Y.Escape.html(e.prevVal + &quot;&quot;)
            + &#x27;&lt;&#x2F;li&gt;&lt;li&gt;e.newVal: &#x27;
            + Y.Escape.html(e.newVal + &quot;&quot;)
            + &#x27;&lt;&#x2F;li&gt;&lt;&#x2F;ul&gt;&lt;&#x2F;div&gt;&#x27;;
        }

        str += &#x27;&lt;&#x2F;div&gt;&#x27;;
 
        Y.one(&quot;#example-out&quot;).prepend(str);
    }

    &#x2F;&#x2F; Start Example Form Handling
    var attrSel = Y.one(&quot;#attrSel&quot;);
    var newValTxt = Y.one(&quot;#newVal&quot;);
    var currentValSpan = Y.one(&quot;#currentVal&quot;);
    var preventFoobarChk = Y.one(&quot;#preventFoobar input[type=checkbox]&quot;);
    var preventFoobarLbl = Y.one(&quot;#preventFoobar&quot;);

    var attrOpts = attrSel.get(&quot;options&quot;);

    function updateVal() {
        var selIndex = attrSel.get(&quot;selectedIndex&quot;);
        var attr = attrOpts.item(selIndex).get(&quot;value&quot;);
        o1.set(attr, newValTxt.get(&quot;value&quot;));
    }

    Y.on(&quot;click&quot;, updateVal, &quot;#changeValue&quot;);

    function populateCurrentValue() {
        var selIndex = attrSel.get(&quot;selectedIndex&quot;);
        var attr = attrOpts.item(selIndex).get(&quot;value&quot;);

        currentValSpan.set(&quot;innerHTML&quot;, Y.Escape.html(o1.get(attr) + &quot;&quot;));
        newValTxt.set(&quot;value&quot;, &quot;&quot;);

        if (attr === &quot;foobar&quot;) {
            preventFoobarLbl.removeClass(&quot;hidden&quot;);
        } else {
            preventFoobarLbl.addClass(&quot;hidden&quot;);
        }
    }

    populateCurrentValue();

    Y.on(&quot;change&quot;, populateCurrentValue, attrSel);
    &#x2F;&#x2F; End Example Form Handling

    &#x2F;&#x2F; Attribute Change Event Listners

    o1.after(&quot;fooChange&quot;, function(e) {
        displayEvent(e, &quot;After fooChange&quot;);
        currentValSpan.set(&quot;innerHTML&quot;, Y.Escape.html(e.newVal+&quot;&quot;));
    });

    o1.after(&quot;barChange&quot;, function(e) {
        displayEvent(e, &quot;After barChange&quot;);
        currentValSpan.set(&quot;innerHTML&quot;, Y.Escape.html(e.newVal+&quot;&quot;));
    });

    o1.on(&quot;foobarChange&quot;, function(e) {

        if (preventFoobarChk.get(&quot;checked&quot;)) {

            &#x2F;&#x2F; Calling preventDefault, in an &quot;on&quot; listener
            &#x2F;&#x2F; will prevent the attribute change from occuring
            &#x2F;&#x2F; and the after listener being called.

            e.preventDefault();
            displayEvent(null, &quot;On foobarChange (prevented)&quot;);
        }

    });

    o1.after(&quot;foobarChange&quot;, function(e) {

        &#x2F;&#x2F; This foobar after listener will not get called, 
        &#x2F;&#x2F; if we end up preventing default in the &quot;on&quot; 
        &#x2F;&#x2F; listener above.

        displayEvent(e, &quot;After foobarChange&quot;);
        currentValSpan.set(&quot;innerHTML&quot;, Y.Escape.html(e.newVal+&quot;&quot;));
    });

});
&lt;&#x2F;script&gt;</pre>

</div>
        </div>

        <div id="sidebar" class="yui3-u">
            

            
                <div class="sidebox">
                    <div class="hd">
                        <h2 class="no-toc">Examples</h2>
                    </div>

                    <div class="bd">
                        <ul class="examples">
                            
                                
                                    <li data-description="Use the Attribute API to define, set and get attribute values.">
                                        <a href="attribute-basic.html">Basic Attribute Configuration</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Configure attributes to be readOnly or writeOnce.">
                                        <a href="attribute-rw.html">Read-Only and Write-Once Attributes</a>
                                    </li>
                                
                            
                                
                                    <li data-description="How to listen for changes in attribute values.">
                                        <a href="attribute-event.html">Attribute Change Events</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Create a basic SpeedDater class, with Attribute support.">
                                        <a href="attribute-basic-speeddate.html">Attribute Based Speed Dating</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Refactors the basic Speed Dating example, to use attribute change events to update rendered elements, and have two instances react to another.">
                                        <a href="attribute-event-speeddate.html">Attribute Event Based Speed Dating</a>
                                    </li>
                                
                            
                                
                                    <li data-description="Add custom methods to get and set attribute values and provide validation support.">
                                        <a href="attribute-getset.html">Attribute Getters, Setters and Validators</a>
                                    </li>
                                
                            
                        </ul>
                    </div>
                </div>
            

            
        </div>
    </div>
</div>

<script src="../assets/vendor/prettify/prettify-min.js"></script>
<script>prettyPrint();</script>

</body>
</html>
